'''
Created on 18/03/2009

@author: eh01
'''
from im.event import eventconstants
from im.event.exception.eventhandlerexception import \
    EventHandlerNotFoundException, EventHandlerExecutionException
from im.event.event import Event
from im.ds import dsconstants, dsofactory
import traceback
import datetime
import threading


class EventDispatcher(threading.Thread):
    '''
    classdocs
    '''

    def __init__(self, eventQueue, eventHandlers):
        '''
        Constructor
        '''
        self.__eventQueue = eventQueue
        self.__eventHandlers = eventHandlers
        threading.Thread.__init__(self)

    def get_eventQueue(self):
        return self.__eventQueue


    def get_eventHandlers(self):
        return self.__eventHandlers


    def set_eventQueue(self, value):
        self.__eventQueue = value


    def set_eventHandlers(self, value):
        self.__eventHandlers = value

    eventQueue = property(get_eventQueue, set_eventQueue, None, None)

    eventHandlers = property(get_eventHandlers, set_eventHandlers, None, None)

    def get_eventHandler(self, event):
        eventType = event.get_type()
        try:
            eventHandler = self.__eventHandlers[eventType]
        except KeyError:
            raise EventHandlerNotFoundException("Event Handler for type " + eventType + " cannot be found")
        return eventHandler
            
    def run(self):
        while True:
            event = self.__eventQueue.get()
            if event.get_type() is "STOP":
                break
            try:
                eventHandler = self.get_eventHandler(event)
            except EventHandlerNotFoundException, e:
                print e.reason
                continue
            
            try:
                print 'start ' + eventHandler.__class__.__name__ + ': ' + str(datetime.datetime.now())
                eventHandler.do(event.get_data())
                print 'end ' + eventHandler.__class__.__name__ + ': ' + str(datetime.datetime.now())
            except EventHandlerExecutionException, e:
                print e.reason
                traceback.print_exc()
            except Exception, e:
                print e
                traceback.print_exc()